package dingding;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserListidRequest;
import com.dingtalk.api.request.OapiUserListsimpleRequest;
import com.dingtalk.api.response.OapiCalendarListResponse.User;
import com.dingtalk.api.response.OapiUserListidResponse;
import com.dingtalk.api.response.OapiUserListsimpleResponse;
import com.taobao.api.ApiException;

import dingding.entity.TopEntity;

/**
 * 获取钉钉用户 userid
 * @author ljl
 *
 */
public class UserList {
	 public List<String> getUserId() throws Exception {
		 ArrayList<String> arrayList=new ArrayList<String>(); //用户dept_id list
		 DepartMentList dpl =  new DepartMentList();
		 List<String> dpls = dpl.getDepartMent();
//		 System.out.println("dpls"+dpls);
		 
		// 获取服务端接口调用凭证access_token
	     String access_token = AccessTokenUtil.getToken();
	     DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
	     for (String dp : dpls) {
		     OapiUserListsimpleRequest req = new OapiUserListsimpleRequest();
		     req.setDeptId(Long.parseLong(dp)); 
		     req.setCursor(0L);
		     req.setSize(10L);
		     req.setOrderField("modify_desc");
		     req.setContainAccessLimit(false);
		     req.setLanguage("zh_CN");
		     OapiUserListsimpleResponse rsp = client.execute(req, access_token);
//		     System.out.println("rsp" +rsp.getBody());
		     
		  // 把json字符串转为json对象
//		     System.out.println(rsp.getBody());
//		     JSONObject jsonObj = JSONObject.parseObject(rsp.getBody());
//		     String result = jsonObj.getString("result");
//		     JSONObject jsonObj2 = JSONObject.parseObject(result);
//		     String users = jsonObj2.getString("list");
//		     System.out.println(users);
//		     JSONArray arry = JSONObject.parseArray(users);
		    
//	         for (Object object : arry) { 
//	        	arrayList.add(JSONObject.parseObject(object.toString()).getString("userid"));
//			 }
		     TopEntity aa = JSONObject.parseObject(rsp.getBody(),TopEntity.class);
    	
		     for (dingding.entity.User u : aa.getResult().getList()) {
//		    	 System.out.println("aa:"+JSONObject.toJSONString(u));
//		    	 System.out.println(u.getName());
		    	 arrayList.add(u.getUserid());
			}
				
		}
	     
	     return arrayList;
	    
	 }
}
